from QQLoginTool.QQtool import OAuthQQ
from django.shortcuts import render

# Create your views here.


# GET/oauth/qq/statues/?state=xxx
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_jwt.settings import api_settings

from mall import settings
from oauth.models import OAuthQQUser
from oauth.serializers import OauthQQUserAPIViewSerialzier
from users.serializers import UserInfoAPIViewSerializer
from utils.utils import generate_save_token

'''
１　在登陆页面　已经进行实现用户名和手机号同时可以登陆　现在实现的是第三方登陆
２　点击第三方的登陆　跳转　前端请求　后端将地址发送给前端　
３　用户点击确认　由第三方返回一个code  前端将code 发送给后端　
４　后端用code 访问第三方网站　用code 去换取token
５　再用token 去换取openid
６　将openid 发送给前端　由前端请求新的绑定页面　绑定页面　
７　需要的参数　openid mobile password sms_code

'''


# 主要返回给前端第三方的登陆网址
class OauthQQAPIVIew(APIView):

    def get(self,request):
        state = request.query_params.get('state')
        if not state:
            state = '/'

        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI, state=state)

        login_url = oauth.get_qq_url()

        return Response({'login_url':login_url})



'''
GET /oauth/qq/users/?code=xxx
１　这个是由用户确认之后　由第三方返回给前端的code
２　我们需要前端将这个传回来
３　我们拿着这个code 去换取token
４　我们再用token 去换取openid

'''
'''
         POST /oauth/qq/users/
         １　参数　openid 手机号　密码　　sms_code   进行绑定
         ２　接收参数　
         ３　序列化器的选择　M
         ４　进行验证
         ５　进行从写create
         ６　返回响应

        '''


class OauthQQUserAPIView(APIView):

    def get(self,request):
        code = request.query_params.get('code')

        if not code:

            return Response({'msm_code':'缺少code'},status=status.HTTP_400_BAD_REQUEST)

        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI)
        try:
            access_token = oauth.get_access_token(code)

            openid = oauth.get_open_id(access_token)

        except Exception:
            return Response({'mssage':'第三方服务器错误'},status=status.HTTP_502_BAD_GATEWAY)

        try:
            user = OAuthQQUser.objects.get(openid = openid)
        except OAuthQQUser.DoesNotExist:
            openid = generate_save_token(openid)

            return Response({'access_token':openid})

        else:
            '''
            说明openid 存在　所以现在要将openid  和　user_id username 返回
            '''

        # 注册完成的时候需要将token返回　在序列化器中　创建token 的值　
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        # 看模型的字段　就会明白
        payload = jwt_payload_handler(user.user)
        token = jwt_encode_handler(payload)

        return Response({
            'token':token,
            'user_id':user.user.id,
            'username':user.user.username

        })

    def post(self,request):

        # １　参数　openid 手机号　密码　　sms_code   进行绑定
        # ２　接收参数　
        data = request.data
        # ３　序列化器的选择　M
        serializer = OauthQQUserAPIViewSerialzier(data=data)
        # ４　进行验证
        serializer.is_valid(raise_exception=True)
        # ５　进行从写create
        user = serializer.save()

        # 注册完成的时候需要将token返回　在序列化器中　创建token 的值　
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user.user)
        token = jwt_encode_handler(payload)

        data = {
            'token':token,
            'id':user.user.id,
            'username':user.user.username
        }

        # ６　返回响应
        return Response(data)



